from django.shortcuts import render,redirect,HttpResponse
from django.http import JsonResponse
from stuInfo.models import  CarInfo,CancelCarInfo
from stuInfo.utils.pagination import Pagination
from django.forms import ModelForm,Form
from django import forms
from django.core.exceptions import ValidationError
import re
import datetime
import copy

class CarAddForm(ModelForm):
    south_gate = forms.BooleanField(label="南门权限",required=False)
    east_gate = forms.BooleanField(label="东门权限",required=False)
    west_gate = forms.BooleanField(label="西门权限",required=False)
    southeast_gate = forms.BooleanField(label="东南门权限",required=False)
    class Meta:
        model = CarInfo
        # exclude = ["create_date "]
        fields = "__all__"

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            if name in  ["south_gate","east_gate","west_gate","southeast_gate"]:
                continue
            field.widget.attrs = {"class":"form-control","placeholder":field.label,"autocomplete":"off"}

    def clean_car_number(self):
        txt = self.cleaned_data['car_number']
        obj = re.compile('^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$')
        if obj.match(txt):
            return txt
        raise ValidationError("车牌号输入错误")

    def clean_phone_number(self):
        txt = self.cleaned_data['phone_number']
        obj = re.compile("^1[3-9]\\d{9}$")
        if obj.match(txt):
            return txt
        raise ValidationError("手机号码输入有误")

    def clean_car_number(self):
        txt = self.cleaned_data['car_number']
        database_car_number = CarInfo.objects.filter(car_number=txt)
        if self.instance and self.instance.car_number == txt:
            return txt
        if database_car_number:
            raise ValidationError("该车辆已存在，不允许重复授权")
        return txt


    

# 车辆管理首页
def car_index(request):
    queryset = request.GET
    # 保留搜索参数
    global param
    # queryset_dict = copy.deepcopy(request.GET)
    # queryset_dict._mutable = True
    param = "?"+ queryset.urlencode()
    name = request.GET.get('name','')
    car_no = request.GET.get('car_no','')
    category = request.GET.get('category','')
    queryset = CarInfo.objects.filter(name__contains=name,car_number__contains=car_no,category__contains=category)
    # queryset = CarInfo.objects.all()
    page_object = Pagination(request,queryset)
    page_queryset = page_object.page_queryset
    page_str = page_object.html()[0]
    page_info = page_object.html()[1]
    page_id_start = page_object.html()[2]

    return render(request,'car_index.html',{
        "queryset":page_queryset,
        "page_str" :page_str,
        "page_info" :page_info,
        "page_id_start":page_id_start,
        "name":name,
        "car_no":car_no,
        "category":category,
    })

# 添加车辆
def car_add(request):
    list = ['active', 'inactive', 'archived'] 
    if request.method == "GET":
        form = CarAddForm()
        return render(request,"car_change.html",{
            "form":form,
            "list":list,
        })
    form = CarAddForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/car/index/')
    return render(request,'car_change.html',{
        "form":form,
        "list":list,
    })

def car_edit(request,nid=1):
    data = CarInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        form = CarAddForm(instance=data)
        return render(request,"car_change_cancel.html",{
            "form":form,
            "data":data
        })
    form = CarAddForm(data=request.POST,instance=data)
    if form.is_valid():
        form.save()
        return redirect(f"/car/index/" + param)
    return render(request,"car_change.html",{
        "form":form,
    })



def car_delete(request,nid):
    name = CarInfo.objects.filter(id=nid).first().name
    department = CarInfo.objects.filter(id=nid).first().department
    dep_detail = CarInfo.objects.filter(id=nid).first().dep_detail
    car_number = CarInfo.objects.filter(id=nid).first().car_number
    phone_number = CarInfo.objects.filter(id=nid).first().phone_number
    category = CarInfo.objects.filter(id=nid).first().category
    reason = request.GET.get("reason")
    CancelCarInfo.objects.create(name=name,department=department,car_number=car_number, \
                                 dep_detail=dep_detail,phone_number=phone_number, \
                                 category=category,reason=reason
                                 )
    CarInfo.objects.filter(id=nid).delete()
    return JsonResponse({"status":True})



global cancel_car_list_param
def cancel_car_list(request):
    global cancel_car_list_param
    cancel_car_list_param = request.GET.urlencode()
    name = request.GET.get('name','')
    car_no = request.GET.get('car_no','')
    category = request.GET.get('category','')
    queryset = CancelCarInfo.objects.filter(name__contains=name,car_number__contains=car_no,category__contains=category)
    page_object = Pagination(request,queryset)
    page_queryset = page_object.page_queryset
    page_str = page_object.html()[0]
    page_info = page_object.html()[1]
    page_id_start = page_object.html()[2]
    dict = {
        "queryset":page_queryset,
        "page_str":page_str,
        "page_info":page_info,
        "page_id_start":page_id_start,
        "name":name,
        "car_no":car_no,
        "category":category,
    }

    return render(request,"cancel_car_list.html",dict)

def car_cancel_edit(request,nid):
    data_cancel = CancelCarInfo.objects.filter(id=nid).first()
    if request.method == "GET":
            form = CarAddForm(instance=data_cancel)
            return render(request,"car_change.html",{
                "form":form,
            })
    form = CarAddForm(data=request.POST)
    if form.is_valid():
        form.save()
        CancelCarInfo.objects.filter(id=nid).delete()
        return redirect(f"/car/cancel_car_list/?" + cancel_car_list_param)
    return render(request,"car_change.html",{
        "form":form,
    })

def car_cancle_delete(request,nid):
    CancelCarInfo.objects.filter(id=nid).delete()
    return JsonResponse({"status":True})